const express = require('express');
const nodemailer = require('nodemailer');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const port = 3000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 提供静态文件
app.use(express.static(path.join(__dirname)));

// 根路径处理程序
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.get('/register.html', (req, res) => {
  res.sendFile(path.join(__dirname, 'register.html'));
});

let verificationCode = '';

app.post('/send-code', (req, res) => {
  const email = req.body.email;
  verificationCode = Math.floor(100000 + Math.random() * 900000).toString();

  const transporter = nodemailer.createTransport({
    host: 'smtp.qq.com',
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
      user: 'your-qq-email@qq.com', // 替换为你的QQ邮箱地址
      pass: 'your-authorization-code' // 替换为你的QQ邮箱授权码
    }
  });

  const mailOptions = {
    from: 'your-qq-email@qq.com', // 替换为你的QQ邮箱地址
    to: email,
    subject: '验证码',
    text: `您的验证码是: ${verificationCode}`
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      console.error('发送验证码失败:', error);
      return res.status(500).send('发送验证码失败');
    }
    console.log('验证码已发送:', info.response);
    res.status(200).send('验证码已发送');
  });
});

app.post('/verify-code', (req, res) => {
  const code = req.body.code;
  if (code === verificationCode) {
    res.status(200).send('验证码正确');
  } else {
    res.status(400).send('验证码错误');
  }
});

app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});
